<?php
/**
 * Created by PhpStorm.
 * User: Sunqj
 * Date: 2017/1/19
 * Time: 下午8:21
 */

namespace app\admin\controller;

use app\common\model\Settings;
use think\Exception;
use think\Db;
use app\common\model\Message;

class Category extends Common
{
    public function index()
    {
        //设置标题
        $this->templateTitle("分类管理");
        //获取所有的一级分类
        $categoryList1 = Db::name("category")
            ->where("is_valid", 1)
            ->where("parent_id", 0)
            ->order("display_order DESC,id DESC")
            ->select();

        //隐藏二级分类和三级分类
        //获取所有二级分类
        foreach ($categoryList1 as &$category1) {
            $categoryList2 = Db::name("category")
                ->where("is_valid", 1)
                ->where("parent_id", $category1["id"])
                ->order("display_order DESC,id DESC")
                ->select();

            //获取三级分类
//            foreach ($categoryList2 as &$category2) {
//                $categoryList3 = Db::name("category")
//                    ->where("is_valid", 1)
//                    ->where("parent_id", $category2["id"])
//                    ->order("display_order DESC,id DESC")
//                    ->select();
//
//                $category2["children"] = $categoryList3;
//            }

            $category1["children"] = $categoryList2;
        }

        $this->assign("list1", $categoryList1);

        return $this->fetch();
    }

    //添加分类
    public function add()
    {
        //判断是否为添加子分类
        $parentId = request()->has("parent_id")
            ? request()->param("parent_id") : 0;

        //渲染
        if (request()->isGet()) {
            $this->layoutModal();
            //渲染父级对象
            $parent = Db::name("category")
                ->where("id", $parentId)
                ->where("is_valid", 1)
                ->find();

            $this->assign("parent", $parent);

            return $this->fetch();
        }

        //处理
        if (request()->isAjax()) {
            //创建数据
            $data = array(
                "parent_id" => $parentId,
                "is_valid" => 1,
                "create_time" => now_datetime(),
                "update_time" => now_datetime(),
            );
            //分类名称
            $data["title"] = request()->param("title");
            //分类描述
            $data["description"] = request()->param("desc");
            //分类图标
            $data["img_url"] = request()->param("thumb");
            //分类排序
            $data["display_order"] = request()->param("order");
            //是否显示
            $data["is_visible"] = request()->param("visible");

            try {
                //获取上级分类
                $parent = Db::name("category")
                    ->where("id", $parentId)
                    ->where("is_valid", 1)
                    ->find();

                $categoryId = Db::name("category")->insertGetId($data);

                //ID路径
                if ($parent) {
                    $data = array(
                        "level" => $parent["level"] + 1,
                        "id_path" => $parent["id_path"] . "-" . $categoryId,
                        "title_path" => $parent["title_path"] . "-" . $data["title"],
                    );
                } else {
                    $data = array(
                        "level" => 1,
                        "id_path" => "0-" . $categoryId,
                        "title_path" => $data["title"],
                    );
                }

                //更新分类ID路径
                Db::name("category")
                    ->where("id", $categoryId)
                    ->update($data);
                Settings::saveCategory();//将分类保存到缓存
                /*操作记录*/
                Message::admin_log(0, "后台添加分类");
                return $this->ajaxSuccess("添加新分类成功！");
            } catch (Exception $exception) {
                return $this->ajaxError("添加新分类失败！");
            }
        }
    }

    //更改分类的可见性
    public function visible()
    {
        if (request()->isAjax()) {
            //分类ID
            $categoryId = request()->param("cid");
            //获取可见性状态
            $status = request()->param("status");

            try {
                //修改分类及其子类的可见性
                Db::name("category")
                    ->where("id", $categoryId)
                    ->setField("is_visible", $status);
                Settings::saveCategory();//将分类保存到缓存
                /*操作记录*/
                Message::admin_log(0, "后台修改分类的状态");
                return $this->ajaxSuccess("修改分类可见性成功！");
            } catch (Exception $exception) {
                return $this->ajaxError("修改分类可见性失败！");
            }
        }
    }
    //更改分类是否首页推荐
    public function isIndex()
    {
        if (request()->isAjax()) {
            //分类ID
            $categoryId = request()->param("cid");
            //获取可见性状态
            $status = request()->param("status");
            try {
                //修改分类及其子类的可见性
                Db::name("category")
                    ->where("id", $categoryId)
                    ->setField("is_index", $status);
                Settings::saveCategory();//将分类保存到缓存
                /*操作记录*/
                Message::admin_log(0, "后台修改分类是否首页显示");
                return $this->ajaxSuccess("修改分类首页显示成功！");
            } catch (Exception $exception) {
                return $this->ajaxError("修改分类首页显示失败！");
            }
        }
    }

    //编辑分类
    public function edit()
    {
        //分类ID
        $categoryId = request()->param("cid");

        if (request()->isGet()) {
            $this->layoutModal();

            //获取分类信息
            $category = Db::name("category")
                ->alias("c")
                ->join("__CATEGORY__ p", "p.id=c.parent_id", "LEFT")
                ->where("c.id", $categoryId)
                ->field("c.*,p.title AS parent_title")
                ->find();
            $this->assign("category", $category);
            $this->assign("single_image", array("thumb" => $category["img_url"]));

            return $this->fetch();
        }

        if (request()->isAjax()) {
            //
            //创建数据
            $data = array(
                "update_time" => now_datetime(),
            );
            //分类名称
            $data["title"] = request()->param("title");
            //分类描述
            $data["description"] = request()->param("desc");
            //分类图标
            $data["img_url"] = request()->param("thumb");
            //分类排序
            $data["display_order"] = request()->param("order");
            //是否显示
            $data["is_visible"] = request()->param("visible");

            try {

                //更新分类ID路径
                Db::name("category")
                    ->where("id", $categoryId)
                    ->update($data);
                Settings::saveCategory();//将分类保存到缓存
                /*操作记录*/
                Message::admin_log(0, "后台修改分类");
                return $this->ajaxSuccess("更新分类成功！");
            } catch (Exception $exception) {
                return $this->ajaxError("更新分类失败！");
            }
        }
    }

    //编辑全部
    public function editAll()
    {
        //分类ID
        $categoryId = 1;

        if (request()->isGet()) {
            $this->layoutModal();

            //获取分类信息
            $category = Db::name("category_all")
                ->where("id", $categoryId)
                ->find();
            $this->assign("category", $category);
            $this->assign("single_image", array("thumb" => $category["img_url"]));

            return $this->fetch();
        }

        if (request()->isAjax()) {
            //
            //创建数据
            $data = array(
                "update_time" => now_datetime(),
            );
            //分类名称
            $data["title"] = request()->param("title");
            if (empty($data['title'])) {
                return $this->ajaxError('请输入名称');
            }
            //分类描述
            $data["description"] = request()->param("desc");
            //分类图标
            $data["img_url"] = request()->param("thumb");
            if (empty($data['img_url'])) {
                return $this->ajaxError('请上传分类图标');
            }
            //是否显示
            //$data["is_visible"] = request()->param("visible");

            try {
                //更新分类ID路径
                Db::name("category_all")
                    ->where("id", $categoryId)
                    ->update($data);
                Settings::saveCategory();//将分类保存到缓存
                /*操作记录*/
                Message::admin_log(0, "后台批量修改分类");
                return $this->ajaxSuccess("编辑成功！");
            } catch (Exception $exception) {
                return $this->ajaxError("编辑失败！");
            }
        }
    }

    //删除分类
    public function remove()
    {
        if (request()->isAjax()) {
            //获取分类ID
            $categoryId = request()->param("cid");

            try {
                Db::name("category")
                    ->where("id", $categoryId)
                    ->setField("is_valid", 0);
                Settings::saveCategory();//将分类保存到缓存
                /*操作记录*/
                Message::admin_log(0, "后台删除分类");
                return $this->ajaxSuccess("删除分类成功！");
            } catch (Exception $exception) {
                return $this->ajaxError("删除分类失败！");
            }
        }
    }

    //还原
    public function reduction()
    {
        if (request()->isAjax()) {
            //获取分类ID
            $categoryId = request()->param("id");

            try {
                Db::name("category")
                    ->where("id", $categoryId)
                    ->setField("is_valid", 1);
                Settings::saveCategory();//将分类保存到缓存
                /*操作记录*/
                Message::admin_log(0, "后台还原分类");
                return $this->ajaxSuccess("还原分类成功！");
            } catch (Exception $exception) {
                return $this->ajaxError("还原分类失败！");
            }
        }
    }

    //彻底删除
    public function deletes()
    {
        if (request()->isAjax()) {
            //获取分类ID
            $categoryId = request()->param("id");
            $info = Db::name("category")
                ->where("id", $categoryId)
                ->find();
            try {
                Db::name("category")
                    ->where("id", $categoryId)
                    ->delete();

                if ($info['level'] == 1) {
                    //删除与品牌关联
                    Db::name('category_brand')->where('category_id1', $categoryId)->delete();
                    //删除与商家关联
                    Db::name('category_business')->where('category_id1', $categoryId)->delete();
                }
                Settings::saveCategory();//将分类保存到缓存
                /*操作记录*/
                Message::admin_log(0, "后台彻底删除分类");
                return $this->ajaxSuccess("彻底删除分类成功！");
            } catch (Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                return $this->ajaxError($exception->getMessage());
            }
        }
    }

    public function recycle()
    {
        if (request()->isGet()) {
            //设置标题
            $this->templateTitle("分类回收站");

            //获取所有用户
            $list = Db::name("category")
                ->where('is_valid', 'neq', 1)
                ->paginate(15);

            $this->assign("list", $list);

            return $this->fetch();
        }
    }

}